package com.sline.Test;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo2_FileTransferServer {
    public static void main(String[] args) throws IOException {
        ServerSocket server = new ServerSocket(2233);

        while (true) {
            Socket socket = server.accept();
            new Thread() {
                @Override
                public void run() {
                    try {
                        InputStream is = socket.getInputStream();
                        BufferedReader br = new BufferedReader(new InputStreamReader(is));
                        PrintStream ps = new PrintStream(socket.getOutputStream());

                        String fileName = br.readLine();
                        File dir = new File("upload");
                        dir.mkdir();
                        File file = new File(dir, fileName);

                        System.out.println("服务端收到请求" + fileName);
                        if (file.exists()) {
                            ps.println("存在");
                            socket.close();
                        } else {
                            ps.println("请上传");
                        }


                        FileOutputStream fos = new FileOutputStream(file);
                        byte[] arr = new byte[8192];
                        int len;

                        while ((len = is.read(arr)) != -1) {
                            fos.write(arr, 0, len);
                        }

                        fos.close();
                        socket.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }.start();
        }
    }
}
